package com.fenyin.samples.study.jdk.nio.channels.tcp.server.reactor;  

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
  
/**
 * 
 *@Description: 业务处理线程 
 *@Author:fengzhichao  
 *@Since:2012-12-3  
 *@Version:1.1.0
 */
public class Handler implements Runnable {  
  
    private static final int READ_STATUS  = 1;  
  
    private static final int WRITE_STATUS = 2;  
  
    private SocketChannel socketChannel;  
  
    private SelectionKey selectionKey;  
  
    private int status= READ_STATUS;  
    
    /**日志处理实例*/
	private static final Log log = LogFactory.getLog(Handler.class);
  
    public Handler(Selector selector, SocketChannel socketChannel) {  
        this.socketChannel = socketChannel;  
        try {  
            socketChannel.configureBlocking(false);  
            selectionKey = socketChannel.register(selector, 0);  
            selectionKey.interestOps(SelectionKey.OP_READ);  
            selectionKey.attach(this);  
            //使尚未返回的第一个选择操作立即返回
            selector.wakeup();  
        } catch (Throwable th) {  
        	log.error("创建Handler异常",th); 
        }  
    }  
  
    public void run() {  
        try {  
        	//先read->write->结束
            if (status == READ_STATUS) {  
                read();
                selectionKey.interestOps(SelectionKey.OP_WRITE);  
                status = WRITE_STATUS;  
            } else if (status == WRITE_STATUS) {  
                process();  
                //请求取消此键的通道到其选择器的注册
                selectionKey.cancel();  
                log.info("服务器发送消息成功!");  
            }  
        } catch (Throwable th) {  
        	log.error("Handler进程异常",th); 
        }  
    }  
  
    public void read() throws IOException {  
        ByteBuffer buffer = ByteBuffer.allocate(1024);  
        socketChannel.read(buffer);  
        log.info("接收到来自客户端（" + socketChannel.socket().getInetAddress().getHostAddress()+ "）的消息：" + new String(buffer.array()));  
    }  
  
    public void process() throws IOException {  
        String content = "Hello World!";  
        ByteBuffer buffer = ByteBuffer.wrap(content.getBytes());  
        socketChannel.write(buffer);  
    }  
}  